#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import logging
from sqlalchemy.orm import Session
from app.db.session import SessionLocal
from app.crud.sys_config import sys_config
from app.schemas.sys_config import SysConfigCreate

logger = logging.getLogger(__name__)


def init_system_configs():
    """初始化系统配置数据"""
    db: Session = SessionLocal()
    
    try:
        # 定义初始配置数据
        initial_configs = [
            {
                'code': 'shipmentTaskFrequency',
                'value': '*/5 * * * *',  # 每5分钟执行一次
                'remarks': '货物监控任务执行频率(Cron表达式)'
            },
            {
                'code': 'shipmentFromMinusMin', 
                'value': '60',
                'remarks': '查询历史轨迹时减去的分钟数'
            },
            {
                'code': 'coordinateErrorRange',
                'value': '300',
                'remarks': '坐标匹配误差范围(米)'
            }
        ]
        
        created_count = 0
        for config_data in initial_configs:
            # 检查配置是否已存在
            existing_config = sys_config.get_by_code(db, code=config_data['code'])
            if not existing_config:
                config_in = SysConfigCreate(**config_data)
                sys_config.create(db, obj_in=config_in, created_by='system')
                created_count += 1
                logger.info(f"已创建系统配置: {config_data['code']}")
            else:
                logger.info(f"系统配置已存在: {config_data['code']}")
        
        logger.info(f"系统配置初始化完成，新增 {created_count} 个配置")
        return created_count
        
    except Exception as e:
        logger.error(f"初始化系统配置失败: {str(e)}")
        db.rollback()
        raise e
    finally:
        db.close()


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    init_system_configs()